﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;
using Mani.Common.WorkflowEngine;
using System.Collections.ObjectModel;
using Mani.Common;

namespace RastinArgham.CRM.Web
{
    public partial class dashboard : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            SecurityManager securityManager = new SecurityManager();
            securityManager.authProvider = new WebAuthorizationProvider();

            if (!securityManager.IsActionPermitted("all_contacts") && !securityManager.IsActionPermitted("my_contacts"))
                Response.Redirect("~/access_denied.aspx");

            if (!Page.IsPostBack) {
                LoadCities();
                LoadOrders();
            }

            Trace.Write("Page Load End: " + DateTime.Now);
        }

        private void LoadCities()
        {
            SecurityManager securityManager = new SecurityManager();
            securityManager.authProvider = new WebAuthorizationProvider();
            CRMRepository crmRepository = new CRMRepository();
            ddlCities.DataSource = crmRepository.FindCitiesByUser(securityManager.authProvider.GetCurrentUser().UserId);
            ddlCities.DataBind();

            if (Session["CurrentCity"] != null)
            {
                ddlCities.ClearSelection();
                ddlCities.Items.FindByValue(Session["CurrentCity"].ToString()).Selected = true;
            }
        }

        private void LoadOrders()
        {
            List<int> contacts = new List<int>();
            List<CountStatus> countStatusList = null;
            int stateId = -1;

            if (Request.QueryString["stateId"] != null)
                Int32.TryParse(Request.QueryString["stateId"], out stateId);

            SecurityManager securityManager = new SecurityManager();
            securityManager.authProvider = new WebAuthorizationProvider();
            CRMRepository crmRepository = new CRMRepository();

            int cityId = -1;
            if (Session["CurrentCity"] == null)
                cityId = Convert.ToInt32(ddlCities.SelectedValue);
            else
                cityId = Convert.ToInt32(Session["CurrentCity"]);

            if (securityManager.IsActionPermitted("all_contacts"))
            {
                countStatusList = crmRepository.GetOrderStatesCount(cityId);
            }
            else
            {
                Guid myId = securityManager.authProvider.GetCurrentUser().UserId;
                List<Guid> myAccountManagers = crmRepository.FindMyAccountManagers(myId);

                if (cityId == -1)
                    contacts = crmRepository.SearchContactIds(myAccountManagers, myId);
                else
                    contacts = crmRepository.SearchContactIds(myAccountManagers, myId, Convert.ToInt32(ddlCities.SelectedValue));

                countStatusList = crmRepository.GetOrderStatsByContacts(contacts);
            }

            rptStats.DataSource = countStatusList;
            rptStats.DataBind();

            
            if (stateId != -1)
            {
                List<Order> orders = null;

                gvOrders.VirtualItemCount = countStatusList.Where(c => c.Status == stateId).Select( c => c.Count).FirstOrDefault();

                if (securityManager.IsActionPermitted("all_contacts"))
                    orders = crmRepository.GetServiceOrders(cityId, stateId, gvOrders.PageSize, gvOrders.PageIndex);
                else
                    orders = crmRepository.SearchServiceOrdersByContacts(contacts, stateId, gvOrders.PageSize, gvOrders.PageIndex);

                gvOrders.DataSource = orders;
                gvOrders.DataBind();
            }
        }

        protected void gvOrders_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow)
                return;

            CRMRepository crmRepository = new CRMRepository();
            SecurityManager securityManager = new SecurityManager();
            securityManager.authProvider = new WebAuthorizationProvider();

            int orderId = Convert.ToInt32(gvOrders.DataKeys[e.Row.RowIndex].Value);
            Order o = crmRepository.GetOrderById(orderId);

            WorkflowBasic wf = WorkflowFactory.Load(o.WorkflowInstanceId.Value);

            string[] roles = securityManager.authProvider.GetCurrentUser().aspnet_Roles.Select(r => r.RoleName).ToArray();
            ReadOnlyCollection<String> events = wf.GetPossibleEvents(roles);

            int i = 1;

            foreach (var item in events)
            {
                LinkButton link = (LinkButton)e.Row.FindControl("lbLink" + i.ToString());
                if (link != null)
                {
                    link.Visible = true;
                    link.Text = wf.GetEventDescription(item);
                    link.CommandName = item;
                    link.CommandArgument = o.WorkflowInstanceId.Value.ToString();
                }

                i++;
            }
        }

        protected void gvOrders_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Page")
                return;

            SecurityManager securityManager = new SecurityManager();
            securityManager.authProvider = new WebAuthorizationProvider();

            WorkflowBasic wf = WorkflowFactory.Load(new Guid(e.CommandArgument.ToString()));

            try
            {
                wf.SendEvent(e.CommandName, securityManager.authProvider.GetCurrentUser().UserId);
                LoadOrders();
            }
            catch (WorkflowException ex)
            {
                UIHelper.ClientAlert(this, ex.ErrorMessage);
            }
        }

        protected void gvOrders_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvOrders.PageIndex = e.NewPageIndex;
            LoadOrders();
        }

        protected void ddlCities_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["CurrentCity"] = ddlCities.SelectedValue;
            LoadOrders();
        }

        public string CheckNotification(object Status)
        {
            int stateId = Convert.ToInt32(Status);

            if (stateId == 88 || stateId == 102 || stateId == 106 || stateId == 5 )
                return "notify";
            else
                return "nothing";
        }
    }
}